<!-- offerForm.vue -->
<template>
	<div v-if="showOfferForm">
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="职位名称" name="positionName">
						<a-input v-model:value="formData.positionName" placeholder="请输入职位名称" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="邮箱" name="offerEmail">
						<a-input v-model:value="formData.offerEmail" placeholder="请输入接收Offer的邮箱地址" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="试用期(月)" name="probationMonths">
						<a-input-number
							v-model:value="formData.probationMonths"
							:min="0"
							:step="1"
							placeholder="请输入试用期月数"
							style="width: 100%"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="基本工资(税前)" name="baseSalary">
						<a-input-number
							v-model:value="formData.baseSalary"
							:min="0"
							:step="1000"
							placeholder="请输入基本工资(税前)"
							style="width: 100%"
							@change="calculateProbationSalary"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="奖金/绩效" name="bonus">
						<a-input-number
							v-model:value="formData.bonus"
							:min="0"
							:step="1000"
							placeholder="请输入奖金/绩效"
							style="width: 100%"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="折扣比例" name="probationSalaryPercent">
						<a-input-number
							v-model:value="formData.probationSalaryPercent"
							:min="0"
							:max="100"
							:step="1"
							placeholder="请输入折扣比例(%)"
							style="width: 100%"
							@change="calculateProbationSalary"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="试用期工资" name="probationSalary">
						<a-input-number
							v-model:value="formData.probationSalary"
							:min="0"
							placeholder="请输入试用期工资"
							style="width: 100%"
						/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="24">
					<a-form-item label="工作地点" name="workLocation">
						<a-select
							v-model:value="formData.workLocation"
							placeholder="请选择工作地点"
							:options="workLocationOptions"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="公司联系人" name="companyContactName">
						<a-input
							@click="companyContactRef.showUserPlusModal()"
							v-model:value="formData.companyContactName"
							placeholder="请选择公司联系人"
							readonly
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="联系电话" name="contactPhone">
						<a-input v-model:value="formData.contactPhone" placeholder="请输入联系电话" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="24">
					<a-form-item label="Offer备注" name="remark">
						<a-textarea v-model:value="formData.remark" placeholder="请输入Offer备注" :rows="4" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<UserSelectorPlus
			ref="companyContactRef"
			data-type="object"
			:user-show="false"
			:radio-model="true"
			@onBack="companyContactCallBack"
		/>
	</div>
</template>

<script setup>
	import { required } from '@/utils/formRules'
	import { computed, reactive, ref, watch } from 'vue'
	import tool from '@/utils/tool'
	import UserSelectorPlus from '@/components/Selector/userSelectorPlus.vue'

	const emit = defineEmits(['update:modelValue'])
	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({
				positionName: undefined,
				offerEmail: undefined,
				probationMonths: 3,
				baseSalary: undefined,
				bonus: undefined,
				probationSalaryPercent: undefined,
				probationSalary: undefined,
				workLocation: undefined,
				positionCode: undefined,
				companyContact: undefined,
				companyContactName: undefined,
				contactPhone: undefined,
				remark: undefined
			})
		},
		sendOffer: {
			type: Boolean,
			default: false
		},
		rules: {
			type: Object,
			default: null
		}
	})

	const currentUser = tool.data.get('USER_INFO')
	const workLocationOptions = [
		{ label: '北京市朝阳区北美国际商务中D座3层', value: '北京市朝阳区北美国际商务中D座3层' },
		{
			label: '天津自贸试验区（空港经济区）中心大道与东二道交口东北侧瑞航广场1号楼2门-301-3',
			value: '天津自贸试验区（空港经济区）中心大道与东二道交口东北侧瑞航广场1号楼2门-301-3'
		},
		{
			label: '江苏省盐城市盐南高新区黄海街道办事处北港村（社区）迎宾南路188号3A-0131室',
			value: '江苏省盐城市盐南高新区黄海街道办事处北港村（社区）迎宾南路188号3A-0131室'
		},
		{
			label: '陕西省西安市经济技术开发区凤城五路111号恒石国际中心B座20层2001/2002室',
			value: '陕西省西安市经济技术开发区凤城五路111号恒石国际中心B座20层2001/2002室'
		},
		{
			label: '宁夏银川市金凤区新昌西路南侧金钻名座1号综合写字楼1702-009室',
			value: '宁夏银川市金凤区新昌西路南侧金钻名座1号综合写字楼1702-009室'
		}
	]

	// 表单引用
	const formRef = ref()
	const companyContactRef = ref()

	// 表单数据
	const formData = reactive({
		positionName: props.modelValue.positionName,
		offerEmail: props.modelValue.offerEmail,
		probationMonths: props.modelValue.probationMonths !== undefined ? props.modelValue.probationMonths : 3,
		baseSalary: props.modelValue.baseSalary,
		bonus: props.modelValue.bonus,
		probationSalaryPercent: props.modelValue.probationSalaryPercent,
		probationSalary: props.modelValue.probationSalary,
		workLocation: props.modelValue.workLocation,
		positionCode: props.modelValue.positionCode,
		companyContact: props.modelValue.companyContact || (currentUser ? currentUser.id : undefined),
		companyContactName: props.modelValue.companyContactName || (currentUser ? currentUser.name : undefined),
		contactPhone: props.modelValue.contactPhone || (currentUser ? currentUser.phone : undefined),
		remark: props.modelValue.remark
	})

	// 控制表单显示
	const showOfferForm = computed(() => props.sendOffer)

	// 表单验证规则
	const formRules = computed(() => {
		if (props.rules) {
			return props.rules
		}
		if (props.sendOffer) {
			return {
				positionName: [required('请输入职位名称')],
				offerEmail: [required('请输入接收Offer的邮箱地址')],
				workLocation: [required('请输入工作地点')],
				positionCode: [required('请输入职位')],
				companyContactName: [required('请选择公司联系人')],
				contactPhone: [required('请输入联系电话')],
				probationMonths: [required('请输入试用期')]
				// baseSalary: [required('请输入基本工资(税前)')],
				// probationSalaryPercent: [required('请输入折扣比例')]
			}
		}
		return {}
	})

	// 计算试用期工资
	const calculateProbationSalary = () => {
		if (formData.baseSalary && formData.probationSalaryPercent) {
			const result = formData.baseSalary * (formData.probationSalaryPercent / 100)
			formData.probationSalary = Math.round(result * 100) / 100
		}
		// 触发更新
		emit('update:modelValue', { ...formData })
	}

	// 公司联系人选择回调
	const companyContactCallBack = (selectUsers) => {
		if (selectUsers && selectUsers.length > 0) {
			const selectedUser = selectUsers[0]
			formData.companyContact = selectedUser.id
			formData.companyContactName = selectedUser.name
			// 联系电话可以保留当前值或更新为选中用户的电话
			if (selectedUser.phone) {
				formData.contactPhone = selectedUser.phone
			}
		}
	}

	// 监听props变化并更新表单数据
	watch(
		() => props.modelValue,
		(newVal) => {
			Object.assign(formData, newVal)
		},
		{ deep: true }
	)

	// 监听表单数据变化并触发更新
	watch(
		formData,
		(newVal) => {
			emit('update:modelValue', { ...newVal })
		},
		{ deep: true }
	)

	// 监听sendOffer变化
	watch(
		() => props.sendOffer,
		(newVal) => {
			// 当sendOffer变为true时，设置默认的公司联系人和电话
			if (newVal && currentUser) {
				if (!formData.companyContact) {
					formData.companyContact = currentUser.id || undefined
					formData.companyContactName = currentUser.name || undefined
				}
				if (!formData.contactPhone) {
					formData.contactPhone = currentUser.phone || undefined
				}
			}
			if (!newVal) {
				formData.offerEmail = undefined
				formData.probationMonths = 3
				formData.baseSalary = undefined
				formData.bonus = undefined
				formData.probationSalaryPercent = 80
				formData.probationSalary = undefined
				formData.workLocation = undefined
				formData.positionCode = undefined
				formData.remark = undefined
				// 注意：不清空 companyContact 和 contactPhone，因为它们可能是默认值
			}
		},
		{ immediate: true }
	)

	// 验证表单
	const validate = () => {
		return formRef.value?.validate()
	}

	// 重置表单
	const resetFields = () => {
		formRef.value?.resetFields()
	}

	defineExpose({
		validate,
		resetFields
	})
</script>
